﻿var express = require('express'),
    path = require('path'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    fs = require("fs"),
    bodyParser = require('body-parser'),
    app = express(),
    handlebars = require('express-handlebars').create({
        defaultLayout: 'run',
        helpers: {
            section: function(name, options) {
                if (!this._sections) this._sections = {};
                this._sections[name] = options.fn(this);
                return null;
            },
            addOne: function(page, index, options) {
                var lineIndex = (page - 1) * 10 + index + 1;
                return lineIndex >= 10 ? lineIndex : "0" + lineIndex;
            },
            if_chk: function(v1, v2, options) {

                if (v1 == v2) {
                    return options.fn(this);
                } else {
                    return options.inverse(this);
                }
            }
        }
    });

global.rootPath = __dirname;

// view engine setup
app.engine('html', handlebars.engine);
app.set("view engine", "html");
app.set('views', path.join(__dirname, 'views'));
//handlebars.registerPartials(__dirname + '/views/partials');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'assets')));
app.use(express.static(path.join(__dirname, 'assets')));
app.use(express.static(path.join(__dirname, 'modules')));


(function() {
    var sites = require(__dirname + "/assets/json/sites.json");
    sites.sort(function(a, b) {
        return a.index - b.index > 0 ? -1 : 1;
    });
    global.sites = sites;
    global.menus = require(__dirname + "/assets/json/menus.json");
})();

//路由配置
require('./modules/routes_run')(app);
require('./modules/routes_admin')(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


//获取新闻
(function() {
    var newsJsonPath = path.join(global.rootPath, "/assets/json/news.json");
    fs.readFile(newsJsonPath, "utf-8", function(err, data) {
        if (err) {
            console.log(err);
        } else {
            global.news = JSON.parse(data);
        }
    });
})();

Date.prototype.format = function(fmt) {
    if (!this.valueOf())
        return '';
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

module.exports = app;